<?php

namespace Frieza\Modules\Article\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\ali\model\Article\Article as AliArticle;
use Doraemon\model\Member;
use Doraemon\model\NewTag\Tag as dbTag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\TodayArticle;
use Doraemon\model\Article;
use Doraemon\tools\ImgUrl;
use Biz\pockets\excel\DownExcel;





class TodayArticleController extends Controller
{

    const PAGE_SIZE = 20;
    const TAG_ID = 4345;
    const MONTH_ARR = [ '01','02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
    const START_YEAR = 2020;
    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content, $year = 0, $month = 0)
    {
        $tab = new Tab();
        $map = [];
        $groupYearTime = $year > 0 ? $year: date("Y", time());

        $groupMonthTime = $month > 0 ? $month: date("m", time());
        $startGroupTime = strtotime($groupYearTime . "-" . $groupMonthTime . "-01");
        $endGroupTime = strtotime($groupYearTime . "-" . $groupMonthTime . "-01 +1 month -1 day");
        $map['show_time[>=]'] = $startGroupTime;
        $map['show_time[<=]'] = $endGroupTime;
        $map['ORDER'] = ['show_time' => 'DESC'];
        $groupInfo = TodayArticle::getAllArticlesByMap($map);
        $list = [];
        if($groupInfo && is_array($groupInfo) ){
            $article_ids = array_unique(array_column($groupInfo , 'article_id')) ? : [];
            if($article_ids && is_array($article_ids)){
                $article_info = Article::getBatchArticleByIds($article_ids);
                $article_info = array_combine(array_column($article_info , 'aid') , $article_info);
            }
            $ids = AliArticle::getArticleListWhere(['article_status' => AliArticle::STATUS_NORMAL], 'aid');

            foreach($groupInfo as $info){
                $show_time = strtotime(date("Y-m-d" , $info['show_time']));
                $info['show_time'] = $show_time;
//                if($article_info[$info['article_id']] && is_array($article_info[$info['article_id']])){
                    $info['origin_title'] = $article_info[$info['article_id']]['title'];
                    $info['uid'] = $article_info[$info['article_id']]['uid'];
                    $info['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP , $info['cover_pic_id'] ,ImgUrl::IMAGE_SIZE_OP_ORI);
                    $info['right'] = in_array($info['article_id'], $ids) ? '已授权' : '未授权';
                    $list[$show_time] = $info;
//                }
            }
        }
        $childTab = new Tab();
        foreach (self::MONTH_ARR as $month) {
            if ($month == $groupMonthTime) {
                $childTab->add($month, $this->getArticleList($startGroupTime, $endGroupTime, $list), true);
            } else {
                $childTab->addlink($month, url('admin/article/todayarticle/' . $groupYearTime . "/" . $month));
            }
        }

        $tab->addLink('全部',  url('admin/article/today'));

        $thisYear = date('Y',time());
        $yearList = range(self::START_YEAR,$thisYear + 1,1); //从2020年开始
        foreach ($yearList as $year){
            if($groupYearTime == $year){
                $tab->add($year, $childTab, true);
            }else{
                $tab->addLink($year,   url('admin/article/todayarticle/'.$year));
            }
        }

        $content->row($tab);
        return $content
            ->header('')
            ->description(' ')
            ->breadcrumb(['text' => '定时推送任务列表', 'url' => url('admin/push/index')], ['text' => '']);
    }

    private function getArticleList($startGroupTime, $endGroupTime, $groupInfo)
    {
        //每月天数
        $day_sum = (( $endGroupTime -$startGroupTime) / 86400) +1;
        $start_date = date("Y-m-d" , $startGroupTime);
        $month_day_list = [];
        for($i = 0 ;$i<$day_sum;$i++ ){
            $show_time = strtotime($start_date."+".$i." day");
            if($groupInfo[$show_time] && is_array($groupInfo[$show_time])){
                $month_day_list[] = $groupInfo[$show_time];
            }else{
                $month_day_list[]['show_time'] = $show_time;
            }
        }
        $gridModel = new pGridDataModel($month_day_list,count($month_day_list));

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();

            $grid->disablePagination();
            $grid->column('show_time', '展示时间')->display(function(){
                    return date("Y-m-d" ,$this->show_time);
            });
            $grid->column('article_id', '文章id');
            $grid->column("origin_tile", '整屋信息')->display(function () {
                if($this->origin_title){
                    return "<p>原标题:".$this->origin_title."</p><p>作者uid:".$this->uid."</p>";
                }else{
                    return '';
                }

            });;
            $grid->column('title', '推荐标题');
            $grid->column('cover_pic_url', '封面')->image();
            $grid->column('right', '授权');
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                if($actions->row->id >0){
                    $actions->append('<a href="/admin/article/todayarticle/edit/' .$actions->row->show_time.'/'. $actions->row->id . '" class="fa fa-edit">编辑</a>');
                }else{
                    $actions->append('<a href="/admin/article/todayarticle/edit/' .$actions->row->show_time.'/0' . '" class="fa fa-edit">添加</a>');

                }

            });
        });
        $list = $listGrid->render();
        return $list;
    }

    //添加或者修改预算表
    public function edit(Request $request,Content $content ,$show_time = 0,$id = 0)
    {
        $request = $request->all();
        return $content
            ->row(self::editAction($request ,$show_time, $id));
    }

    //修改列表
    public  function editAction($request = []  ,$show_time, $id = 0)
    {
        if($id == 0){
            $data = [];
            $data['show_time'] = $show_time;
        }else{
            $data =  TodayArticle::getById($id);
            $data['category'] = explode(',', $data['tag_category']);
        }
        $tags = dbTag::getAllByWhere(['tag_status' => dbTag::STATUS_NORMAL, 'parent_id' => self::TAG_ID, 'ORDER' => ['tag_sort' => 'ASC']], ['id', 'tag']);
        $tags = array_column($tags, 'tag', 'id');
        $form = new Form($data);
        if($id > 0){
            $form->hidden('id');
        }
        $form->hidden("show_time");
        $form->html('<h7>'.date( "Y-m-d",$data['show_time']).' </h7>',  '推荐时间');
        $form->text("article_id" ,'文章id')->required();
        $form->text("title" , "推荐标题");
        $form->imgUpload('cover_pic_id', '推荐封面', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->multipleSelect("category", '分类')->options($tags);
        $form->action('/admin/article/todayarticle/save');

        return $form->render();
    }


    //提交修改
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $id = $request['id'] ? : 0;
        $show_time = $request['show_time'];
        $article_id =  $request['article_id'];
        $info = Article::getArticle($article_id);
        if(empty($info)){
            $error = new MessageBag([
                'title' => '文章不存在'
            ]);
            return redirect('/admin/article/todayarticle')->with(compact('error'));
        }
        $data = [];
        $data['show_time'] = $show_time;
        $data['title'] = $request['title'] ? : '';
        $data['cover_pic_id'] = $request['cover_pic_id'] ? : '';
        $data['article_id'] = $article_id;
        $data['tag_category'] = implode(',', $request['category']);
        $data['addtime'] = time();
        $data['admin_id'] = Admin::user()->id;
        if($id){
          $rs=   TodayArticle::updateById($id , $data);
        }else{
            // 判断$show_time 是否已经在表里有了
            $existShowTime = TodayArticle::getOneArticle(['show_time' => $show_time]);
            if ($existShowTime) {
                $error = new MessageBag([
                    'title' => '展示时间已经存在'
                ]);
                return redirect('/admin/article/todayarticle')->with(compact('error'));
            }
            $rs = TodayArticle::addArticle($data);
        }
        $year = date("Y" , $show_time);
        $month = date("m",$show_time);
        if($rs){
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/article/todayarticle/'.$year.'/'.$month)->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/article/todayarticle/'.$year.'/'.$month)->with(compact('error'));
        }
    }


    //筛选 数据
    public function getAll(Request $request ,Content $content){

        $pageSize = $request->input("per_page", 20);
        $info = $this->getFilterAricle($request);
        $groupInfo = $info['list'] ? : [];
        $total = $info['total']  ? : 0;
        $list = [];
        if($groupInfo && is_array($groupInfo))
        {
            $article_ids = array_unique(array_column($groupInfo , 'article_id')) ? : [];
            if($article_ids && is_array($article_ids)){
                $article_info = Article::getBatchArticleByIds($article_ids);
                $article_info = array_combine(array_column($article_info , 'aid') , $article_info);
            }
            $ids = AliArticle::getArticleListWhere(['article_status' => AliArticle::STATUS_NORMAL], 'aid');
            foreach($groupInfo as $info){
                if($article_info[$info['article_id']] && is_array($article_info[$info['article_id']])){
                    $info['origin_title'] = $article_info[$info['article_id']]['title'];
                    $info['uid'] = $article_info[$info['article_id']]['uid'];
                    $info['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP , $info['cover_pic_id'] ,ImgUrl::IMAGE_SIZE_OP_ORI);
                    $info['publish_time'] = $article_info[$info['article_id']]['publish_time'];
                    $info['right'] = in_array($info['article_id'], $ids) ? '已授权' : '未授权';
                    $list[] = $info;
                }
            }
        }

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?',$url);
        $export_url = $data_url[1] ? :'';
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel ,$export_url) {
                $grid->paginate($gridModel->getPerPage());
                //筛选
                $grid->disableExport();
                $grid->tools(function ($tools) use ($export_url) {
                    $url = url('/admin/article/today/exportNormarlData?'.$export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
                    $tools->append($button);
                });
                //筛选
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();

                    $filter->column(1/2, function ($filter) {
                        $filter->dropDown('Find', [
                            'article_id' => '文章id',
                            'uid' => 'uid',
                            'nick' => '用户昵称'
                        ]);

                    });
                    $filter->column(1/2, function ($filter) {
                        $filter->between('show_time', '展示时间')->datetime();
                    });
                    //条件展开
                    $filter->expand();
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->column('article_id', '文章id');
                $grid->column("origin_tile", '整屋信息')->display(function () {
                    if($this->origin_title){
                        return "<p>原标题:".$this->origin_title."</p><p>作者uid:".$this->uid."</p>";
                    }else{
                        return '';
                    }
                });;
                $grid->column('title', '推荐标题');
                $grid->column('cover_pic_url', '封面')->image();
                $grid->column('show_time', '展示时间')->display(function(){
                    return date("Y-m-d" ,$this->show_time);
                });
                $grid->column('right', '授权');

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'https://m.haohaozhu.cn/bangyang/'.$actions->row->article_id.'.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \''.$url.'\'
                            });">预览  </a></p>');
                });
            });
        $tab = new Tab();

        $tab->add('全部',$gridList->render() ,true);

        $thisYear = date('Y',time());
        $yearList = range(self::START_YEAR,$thisYear + 1,1);
        foreach ($yearList as $year){
            $tab->addLink($year, url("admin/article/todayarticle/$year"));
        }

        $content->row($tab);
        return $content
            ->header('')
            ->description(' ')
            ->breadcrumb(['text' => '定时推送任务列表', 'url' => url('admin/push/index')], ['text' => '']);
    }


    //filterArticle
    public function getFilterAricle(Request $request)
    {
        $map = [];
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $requestParams = $request->all();
        if($requestParams['uid'] || $requestParams['nick']){
            if($requestParams['nick']){
                $uid =  Member::getUidByNick($requestParams['nick']);
                if($uid){
                    $requestParams['uid'] = $uid;
                }
            }
            $uid = $requestParams['uid'];

            if($uid){
                if($requestParams['show_time']['start'] && $requestParams['show_time']['end']){
                    $sql = "select *,CONV(RIGHT(article_id , 7), 36, 10) as author from today_article_pool where show_time BETWEEN ".strtotime($requestParams['show_time']['start'])." AND ".strtotime($requestParams['show_time']['end'])." having author=".$uid;
                }else{
                    $sql = 'select *,CONV(RIGHT(article_id , 7), 36, 10) as author from today_article_pool  having author='.$uid;
                }
                $groupInfo = TodayArticle::query($sql)->fetchAll();
                $total = count($groupInfo);

            }else{
                $groupInfo = [];
                $total = 0;
            }
        }else{
            if($requestParams['show_time']['start'] && $requestParams['show_time']['end'])
            {
                $map['show_time[<>]'] = [strtotime($requestParams['show_time']['start']),strtotime($requestParams['show_time']['end'])];
            }
            if($requestParams['article_id']){
                $map['article_id'] = $requestParams['article_id'];
            }
            $map['ORDER'] = ['show_time' => 'DESC'];
            $total =  TodayArticle::count($map);

            $map['LIMIT'] = [($page -1)*$pageSize , $pageSize];
            $groupInfo = TodayArticle::getAllArticlesByMap($map);
        }
        return [
            'list' => $groupInfo,
            'total' => $total
        ];
    }

    /*导出数据
     *
     * */
    public function exportNormarlData(Request $request)
    {
        $info = $this -> getFilterAricle($request);
        $list = $info['list'] ? : [];
        $row = [];
        if($list && is_array($list)) {
            $article_ids = array_unique(array_column($list , 'article_id')) ? : [];
            if($article_ids && is_array($article_ids)){
                $article_info = Article::getBatchArticleByIds($article_ids);
                $article_info = array_combine(array_column($article_info , 'aid') , $article_info);
            }
            foreach($list as $info){
                if($article_info[$info['article_id']] && is_array($article_info[$info['article_id']])){
                    $row[] = [
                        'show_time' => date("Y-m-d" , $info['show_time']),
                        'aid' => $info['article_id'],
                        'uid' => $article_info[$info['article_id']]['uid'],
                        'nick' => '',
                        'recomm_title' => $info['title'],
                        'origin_title' => $article_info[$info['article_id']]['title'],

                    ];
                }
            }
        }
        if (!empty($row)){
            $subject['list'] = $row;
            $subject['total'] = count($row);
        }else{
            $subject['list'] = [];
            $subject['total'] =0;
        }
        $reason = '今日整屋';
        $header = ['展示时间','aid','uid', '昵称','推荐标题','原始标题'];
        $letter = range('A', 'F');
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);

        //设置列宽
        $widths = ['A' => 45, 'B' => 45,'E' => 70,'F' => 45];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($subject['list'], $header);
    }



}